//
//  WFRefreshControl.swift
//  WangFangWeiBo
//
//  Created by 王方 on 16/7/16.
//  Copyright © 2016年 wf. All rights reserved.
//

import UIKit

private let WFRefreshControlHeight:CGFloat = 50

//下拉刷新状态
enum WFRefreshControlState:Int {
    //下拉刷新状态
    case Normal = 0
    //松手就刷新状态
    case Pulling = 1
    //正在刷新
    case Refreshing = 2
}
class WFRefreshControl: UIControl {
    //当前下拉刷新状态
    var refreshState:WFRefreshControlState = .Normal{
        didSet{
            switch refreshState {
            case .Normal:
                print("下拉刷新")
                messageLabel.text = "下拉刷新"
                iconImageView.hidden = false
                indicatorView.stopAnimating()
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.iconImageView.transform = CGAffineTransformIdentity
                })
                
                //oldValue是上一次存的值
                if oldValue == .Refreshing {
                    UIView.animateWithDuration(0.25, animations: { () -> Void in
                        self.currentScrowView?.contentInset.top -= WFRefreshControlHeight
                    })
                }
            case .Pulling:
                print("松手就刷新")
                messageLabel.text = "松手就刷新"
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.iconImageView.transform = CGAffineTransformMakeRotation(CGFloat(M_PI))
                })
            case .Refreshing:
                print("正在刷新")
                messageLabel.text = "正在刷新..."
                iconImageView.hidden = true
                indicatorView.startAnimating()
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.currentScrowView?.contentInset.top += WFRefreshControlHeight
                })
                
                //通知外界进行加载数据,发送事件
                sendActionsForControlEvents(.ValueChanged)
           
            
            }
        
        }
    
    }
    
    //当前的滚动视图
    var currentScrowView:UIScrollView?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setUpUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK:  - 懒加载控件
    //下拉箭头
    private lazy var iconImageView:UIImageView = UIImageView(image: UIImage(named: "tableview_pull_refresh"))
    //显示内容
    private lazy var messageLabel:UILabel = {
        let label = UILabel()
        label.font = UIFont.systemFontOfSize(12)
        label.textColor = UIColor.darkGrayColor()
        label.text = "下拉刷新"
        return label
    }()
    
    //风火轮
    private lazy var indicatorView:UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.Gray)
    
    // MARK:  - 初始化控件
    private func setUpUI(){
        backgroundColor = RandomColor()
        
        //添加控件
        addSubview(iconImageView)
        addSubview(messageLabel)
        addSubview(indicatorView)
        
        //用系统自带的约束进行布局
        iconImageView.translatesAutoresizingMaskIntoConstraints = false
        addConstraint(NSLayoutConstraint(item: iconImageView, attribute: .CenterX, relatedBy: .Equal, toItem: self, attribute: .CenterX, multiplier: 1, constant: -35))
        addConstraint(NSLayoutConstraint(item: iconImageView, attribute: .CenterY, relatedBy: .Equal, toItem: self, attribute: .CenterY, multiplier: 1, constant: 0))
        
        messageLabel.translatesAutoresizingMaskIntoConstraints = false
        addConstraint(NSLayoutConstraint(item: messageLabel, attribute: .Leading, relatedBy: .Equal, toItem: iconImageView, attribute: .Trailing, multiplier: 1, constant: 0))
        addConstraint(NSLayoutConstraint(item: messageLabel, attribute: .CenterY, relatedBy: .Equal, toItem: iconImageView, attribute: .CenterY, multiplier: 1, constant: 0))
        
        indicatorView.translatesAutoresizingMaskIntoConstraints = false
        addConstraint(NSLayoutConstraint(item: indicatorView, attribute: .CenterX, relatedBy: .Equal, toItem: iconImageView, attribute: .CenterX, multiplier: 1, constant: 0))
        addConstraint(NSLayoutConstraint(item: indicatorView, attribute: .CenterY, relatedBy: .Equal, toItem: iconImageView, attribute: .CenterY, multiplier: 1, constant: 0))
        
    }
    
    // MARK:  - 将要添加到父控件的时候调用
    override func willMoveToSuperview(newSuperview: UIView?) {
        guard let scrowView = newSuperview as? UIScrollView else {
            return
        }
        //代码执行到这里,视图是一定可以滚动的
        
        self.frame.size = CGSizeMake(scrowView.size.width, WFRefreshControlHeight)
        self.frame.origin.y = -WFRefreshControlHeight
        
        //利用kvo监听父控件的滚动
        scrowView.addObserver(self, forKeyPath: "contentOffset", options: [.New], context: nil)
        currentScrowView = scrowView
    }
    
    //kvo监听方法
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
//        print(currentScrowView?.contentOffset.y)
        guard let scrollview = currentScrowView else {
            return
        }
        
        if scrollview.dragging {
        //表示正在拖动中
            if scrollview.contentOffset.y < -(scrollview.contentInset.top + WFRefreshControlHeight){
                print("松手就刷新")
                //更新状态
                refreshState = .Pulling
            }else  if (scrollview.contentOffset.y >=  -(scrollview.contentInset.top + WFRefreshControlHeight) && refreshState == .Pulling ) {
                print("下拉刷新")
                refreshState = .Normal
            }
            
        } else {
        //表示不再拖动中
            if refreshState == .Pulling {
                refreshState = .Refreshing
                print("正在刷新")
            }
        }
        
    }
    
    //结束刷新,供外界调用
    func endRefreshing(){
        refreshState = .Normal
    }
    
    deinit{
        currentScrowView?.removeObserver(self, forKeyPath: "contentOffset")
    }
}
